package com.ndp.fb.mq.consumer.business.syncbusiness;

import com.ndp.fb.model.business.bo.consumer.BusinessParams;
import com.ndp.fb.model.business.bo.consumer.FacebookResult;
import com.restfb.json.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

/**
 * Created by infi on 2015/3/12.
 */

public abstract class AbstractSyncBusiness {
    private final Logger logger = LoggerFactory.getLogger(AbstractSyncBusiness.class);

    public void syncBusiness(String body, Map<String, String> equipmentMap) {
    	 BusinessParams businessParams = buildBusinessParams(body, equipmentMap);
        try {
            FacebookResult facebookResult = new FacebookResult();
            facebookResult.setHasError(true);
            String className = businessParams.getBusinessClass().getSimpleName();
            Long accountId = businessParams.getAccountId();
            logger.info("开始处理" + className + ",帐号{}的数据" + accountId);
            JsonObject jsonObject = new JsonObject(body);
            if (jsonObject.has("error")) {
                facebookResult.setHasError(true);
            } else if (jsonObject.has("data")) {
                //多线程处理每页500条数据
                saveCache(businessParams,facebookResult,jsonObject);
            }
            if (facebookResult.isHasError()) {
                logger.error("出现异常>>>");
                logger.error("body: "+body);
            } else {
                if (facebookResult.isHasNextPage()) {
                    logger.info(className + "帐号" + accountId + "数据请求未完成,继续请求");
                    nextPage(businessParams,facebookResult.getAfter());
                } else {
                    logger.info(className+"帐号"+accountId+"数据请求完成,处理业务逻辑!");
                }
            }
        } catch (Exception e) {
            logger.error("body length: "+body.length()+"body top 100 char>>"+body.substring(0,100)+"出现异常>>>"+e.getMessage());
            logger.error(e.getMessage(), e);
        }
    }

    protected abstract void nextPage(BusinessParams businessParams, String after);

    protected abstract void saveCache(BusinessParams businessParams,FacebookResult facebookResult,JsonObject jsonObject);

    protected abstract BusinessParams buildBusinessParams(String body, Map<String, String> equipmentMap);


    protected String getVal(Map<String, List<String>> paramsMap, String key) {
        if (paramsMap == null) {
            return null;
        }
        List<String> vals = paramsMap.get(key);
        if (CollectionUtils.isEmpty(vals)) {
            return null;
        }
        return vals.get(0);
    }
}
